import axios, { AxiosRequestConfig } from "axios";
import qs from "qs";

const instance = axios.create();

/**
 * get请求
 * @param url string
 * @param data? any
 * @param config? AxiosRequestConfig
 */
export const get = (url: string, data?: any, config?: AxiosRequestConfig) => {
  config ? config.params = data : config = { params: data };
  return instance.get(url, config);
};

/**
 * post请求 默认json
 * @param url string
 * @param data? any
 * @param config? AxiosRequestConfig
 */
export const post = (url: string, data?: any, config?: AxiosRequestConfig) => {
  return instance.post(url, data, config);
};

/**
 * post请求 转成form
 * 请求头为headers: { 'content-type': 'application/x-www-form-urlencoded' } 使用post请求
 * @param url string
 * @param data? any
 * @param config? AxiosRequestConfig
 */
export const formPost = (url: string, data: any, config?: AxiosRequestConfig) => {
  if (!config) {
    config = {
      headers: {
        "content-type": "application/x-www-form-urlencoded"
      }
    };
  } else {
    !config.headers ? config.headers = {
      "content-type": "application/x-www-form-urlencoded"
    } : config.headers["content-type"] = "application/x-www-form-urlencoded";
  }
  data = qs.stringify(data, { arrayFormat: "brackets" })
  return instance.post(url, data, config);
};